const getNowStr = function () {
  var date = new Date();
  var month = date.getMonth() + 1;
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  var monthDay = date.getDate();
  if (monthDay >= 0 && monthDay <= 9) {
    monthDay = "0" + monthDay;
  }
  var weekDay = date.getDay();
  var weekTips = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
  return date.getFullYear() + '年' + month + '月' + monthDay + '日 ' + weekTips[weekDay];
}

const showFormError = function ($ele, msg) {
  if (typeof($ele) === 'string') {
    $ele = jQuery($ele);
  } else if ((! $ele[0]) || (! $ele.size)) {
    $ele = jQuery($ele);
  }
  if (! $ele.parent().parent().hasClass('has-error')) {
    $ele.parent().parent().addClass('has-error has-feedback');
    if($ele.get(0).tagName === 'SELECT') {
      $ele.after('<span class="glyphicon form-control-feedback" aria-hidden="true"></span><span class="control-error">'+msg+'</span>');
      $ele.one('change',function(){
        clearFormError(this);
      });
    } else {
      $ele.after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span><span class="control-error">'+msg+'</span>');
      $ele.one('keydown',function(){
        clearFormError(this);
      });
    }
  }
  $ele.focus();
}

const clearFormError = function ($ele) {
  if (typeof($ele) === 'string') {
    $ele = jQuery($ele);
  } else if ((! $ele[0]) || (! $ele.size))  {
    $ele = jQuery($ele);
  }
  if ($ele.parent().parent().hasClass('has-error')) {
    $ele.siblings('.glyphicon-remove,.control-error').remove();
    $ele.parent().parent().removeClass('has-error has-feedback');
  }
}

const dateTool = {
    format : function(date, fmt){
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        };
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
            }
        }
        return fmt;
    },
    nowStr : function(){
        var date = new Date();
        var weekTips = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
        return dateTool.format(date, 'yyyy年MM月dd日') + ' ' + weekTips[date.getDay()];
    }
}

const validationTool = {
    form : function(ele){
        let getFieldLabelText = function(ele) {
          let lblTxt = jQuery(ele).parent().siblings('label').text();
          if (lblTxt) {
            lblTxt = lblTxt.replace(/\s/g, '');
          }
          return lblTxt;
        }
        let $form = ele;
        if (typeof(ele) === 'string') {
            $form = jQuery(ele);
        } else if (! ele.size) {
            $form = jQuery(ele);
        }
        // 必填项
        let hasError = false;
        $form.find("[aria-required='true']").each(function(index, element) {
            if (jQuery(element).val() === '') {
                validationTool.show(element, '不能为空');
                hasError = true;
            }
        });
        //普通选择框的校验
        $form.find("[aria-required-select='true']").each(function(index, element) {
          if (jQuery(element).val() === '') {
            let lblTxt = getFieldLabelText(element);
            if (!lblTxt) {
              lblTxt =  '不能为空';
            } else {
              lblTxt = '请选择' + lblTxt;
            }
            showFormError(element, lblTxt);
            hasError = true;
          }
        });
        // 字符串最小位数
        $form.find("[aria-minlength]").each(function(index, element) {
            let minlength = jQuery(element).attr('aria-minlength');
            if ((minlength !== '') && parseInt(minlength)) {
                minlength = parseInt(minlength);
                if (jQuery(element).val().length < minlength) {
                    validationTool.show(element, '不能小于' + minlength + '位');
                    hasError = true;
                }
            }
        });
        // 字符串最大位数
        $form.find("[aria-maxlength]").each(function(index, element) {
          let maxlength = jQuery(element).attr('aria-maxlength');
          if ((maxlength !== '') && parseInt(maxlength)) {
            maxlength = parseInt(maxlength);
            if (jQuery(element).val().length > maxlength) {
              showFormError(element, '不能大于' + maxlength + '位');
              hasError = true;
            }
          }
        });
        // 邮箱校验
        $form.find("[aria-email='true']").each(function(index, element) {
            let email = jQuery.trim(jQuery(element).val());
            if((email !== '') && (!email.match(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/))) {
                validationTool.show(element, '邮箱格式不正确');
                hasError = true;
            }
        });
        // 金额校验
        $form.find("[aria-money]").each(function(index, element) {
          let x = 20;//默认小数点前可输入20位
          let y = 2;//默认保留两位小数
          let digitStr = jQuery(element).attr('aria-money');
          let digit = digitStr.split(",");
          if(digit.length >= 1) {
            x = digit[0] - 1;
          }
          if(digit.length >= 2){
            y = digit[1];
          }
          let reg =new RegExp("(^[1-9](\\d{0,"+ x +"})?(\\.[0-9]{1,"+ y +"})?$)|(^(0){1}$)|(^[0-9]\\.[0-9]([0-9])?$)");

          let money = jQuery.trim(jQuery(element).val());
          if((money !== '') && (!money.match(reg))) {
            showFormError(element, '请输入正确的金额格式');
            hasError = true;
          }
        });
        // 数字校验
        $form.find("[aria-number='true']").each(function(index, element) {
            let number = jQuery.trim(jQuery(element).val());
            if((number !== '') && (!number.match(/^(-)?\d+(\.\d+)?$/))) {
                validationTool.show(element, '必须为数字');
                hasError = true;
            }
        });
        // 正数校验
        $form.find("[aria-number-pos='true']").each(function(index, element) {
            let number = jQuery.trim(jQuery(element).val());
            if((number !== '') && (!number.match(/^(-)?\d+(\.\d+)?$/))) {
                validationTool.show(element, '必须为数字');
                hasError = true;
            }else if(number < 0){
                validationTool.show(element, '必须为正数');
                hasError = true;
            }
        });
        // 整数校验
        $form.find("[aria-number-int='true']").each(function(index, element) {
            let number = jQuery.trim(jQuery(element).val());
            if((number !== '') && (!number.match(/^(-)?\d+(\.\d+)?$/))) {
                validationTool.show(element, '必须为数字');
                hasError = true;
            }else if(number % 1 != 0){
                validationTool.show(element, '必须为整数');
                hasError = true;
            }
        });
        // 小数最多位数
        $form.find("[aria-dec-max]").each(function(index, element) {
            let max = jQuery(element).attr('aria-dec-max');
            if ((max !== '') && parseInt(max)) {
                max = parseInt(max);
                let val = jQuery.trim(jQuery(element).val());
                if((val !== '') && (!val.match(/^(-)?\d+(\.\d+)?$/))) {
                    validationTool.show(element, '必须为数字');
                    hasError = true;
                }else if(val.split('.').length > 1 && val.split('.')[1].length > max){
                    validationTool.show(element, '小数最多' + max + '位');
                    hasError = true;
                }
            }
        });
        // 手机号码
        $form.find("[aria-mobile='true']").each(function(index, element) {
          let phone = jQuery.trim(jQuery(element).val());
          if((phone !== '') && (!phone.match(/^1[0-9]{10}$/))) {
            let lblTxt = getFieldLabelText(element);
            if (!lblTxt) {
              lblTxt =  '格式不正确';
            } else {
              lblTxt = '请输入正确的' + lblTxt;
            }
            showFormError(element, lblTxt);
            hasError = true;
          }
        });
        // 身份证号码
        $form.find("[aria-idno='true']").each(function(index, element) {
          let idNo = jQuery.trim(jQuery(element).val());
          if((idNo !== '') && (!idNo.match(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/))) {
            showFormError(element, "请输入正确的身份证号码");
            hasError = true;
          }
        });

        return ! hasError;
    },
    show : function($ele, msg){
        if (typeof($ele) === 'string') {
            $ele = jQuery($ele);
        } else if ((! $ele[0]) || (! $ele.size)) {
            $ele = jQuery($ele);
        }
        var $error = $ele.parent().parent();
        if($ele.parent().siblings('div[class^="col-sm"]').length > 0){
            $error = $ele.parent();
            $error.prev('label').addClass('has-error');
        }
        if (! $error.hasClass('has-error')) {
            $error.addClass('has-error has-feedback');
            $ele.after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span><span class="control-error">'+msg+'</span>');
            $ele.one('keydown',function(){
                validationTool.clear(this);
            }).one('click',function(){
                validationTool.clear(this);
            });;
        }
        $ele.focus();
    },
    clear : function($ele){
        if (typeof($ele) === 'string') {
            $ele = jQuery($ele);
        } else if ((! $ele[0]) || (! $ele.size))  {
            $ele = jQuery($ele);
        }
        if ($ele.parent().parent().hasClass('has-error') || $ele.parent().hasClass('has-error')) {
            $ele.siblings('.glyphicon-remove,.control-error').remove();
            $ele.parent().parent().removeClass('has-error has-feedback');
        }
        if ($ele.parent().hasClass('has-error')) {
            $ele.parent().removeClass('has-error has-feedback');
            $ele.parent().prev('label').removeClass('has-error');
        }
    }
}

const messageTool = {
    show : function(title,content){
        $('#messageModal .modal-header .modal-title').html(title);
        if(title == null || title === ''){
            $('#messageModal .modal-header .modal-title').hide();
        }else{
            $('#messageModal .modal-header .modal-title').show();
        }
        $('#messageModal .modal-body').html(content);
        if(content == null || content === ''){
            $('#messageModal .modal-body').hide();
        }else{
            $('#messageModal .modal-body').show();
        }
        $('#messageModal').modal('show');
    }
}

const dateToSimpleString = function(date) {
  var year = date.getFullYear();
  var month =(date.getMonth() + 1).toString();
  var day = (date.getDate()).toString();
  if (month.length == 1) {
    month = "0" + month;
  }
  if (day.length == 1) {
    day = "0" + day;
  }
  return year + "-" + month + "-" + day;
}

const dateToString = function(date) {
  var year = date.getFullYear();
  var month =(date.getMonth() + 1).toString();
  var day = (date.getDate()).toString();
  var hour = (date.getHours()).toString();
  var minute = (date.getMinutes()).toString();
  var second = (date.getSeconds()).toString();
  if (month.length == 1) {
    month = "0" + month;
  }
  if (day.length == 1) {
    day = "0" + day;
  }
  if (hour.length == 1) {
    hour = "0" + hour;
  }
  if (minute.length == 1) {
    minute = "0" + minute;
  }
  if (second.length == 1) {
    second = "0" + second;
  }
  return year + "-" + month + "-" + day +" "+ hour +":"+minute+":"+second;
}

const stringToStringDate = function(dateString, formatType) {
  var pattern = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/;
  if(formatType === "yyyy-MM-dd HH:mm:ss") {
    return dateString.replace(pattern, '$1-$2-$3 $4:$5:$6');
  }
  if(formatType === "yyyy-MM-dd") {
    return dateString.replace(pattern, '$1-$2-$3');
  }
  return dateString;
}
export { dateTool, validationTool, messageTool,getNowStr, showFormError, clearFormError, dateToSimpleString, dateToString, stringToStringDate }
